package com.xnew.user.service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import com.xnew.bean.common.SysUserInfo;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONObject;
import com.xnew.constant.Constant;
import com.xnew.menu.bean.Menu;
import com.xnew.menu.service.MenuService;
import com.xnew.utils.IdUtils;
import com.xnew.utils.RedisUtil;

@Component
@Transactional(rollbackFor = Exception.class)
public class LoginService {
	
	@Autowired
	private MenuService menuService;
	@Autowired
	private AuUserService auUserService;
	
	
	
	/**
	 * 处理登录返回信息
	 * @author yangcd
	 * @param user 用户对象
	 * @param dataMap 返回的data数据
	 * @return map 返回map信息
	 * */
	private Map<String, Object> loginReturnMap(SysUserInfo user, Map<String, Object> dataMap) throws Exception{
		//保存用户信息
		String token = "TOKEN:"+IdUtils.getIncreaseIdByNanoTime();
		RedisUtil.set(token, JSONObject.toJSONString(user));
		RedisUtil.set("USER_ID:"+user.getUserInfoNo(), token);
		if(user!=null && user.getCode()!=null && !user.getCode().trim().equals("")){
			RedisUtil.set("SSO_CODE:"+user.getCode(), token);
		}
		String aesKey = "AES_KEY:"+token;
		String aesValue = RandomStringUtils.randomAlphanumeric(16);
		RedisUtil.set(aesKey, aesValue);
		
		RedisUtil.set("USER_ROLE:"+user.getUserInfoNo(), dataMap.get("sysRoleVoList").toString());
//		RedisUtil.expire("USER_ROLE:"+user.getUserId(), 1800);
		
		Map<String, Object> map = new HashMap<String, Object>();
		
		map.put("status", "SUCCESS");
		map.put("message", "登陆成功");
		map.put("token", token);
		map.put("aesKey", aesValue);
		map.put("data", dataMap);
		map.put("sucess", true);
		return map;
		
	}
	
	public List<Map<String,Object>> getRoleByUserId(String auId) throws Exception{
		List<Map<String,Object>> list = auUserService.getRoleByUserId(auId);
		return list;
	}
	
	public List<Map<String,Object>> getResourceByUserId(String auId) throws Exception{
		List<Map<String,Object>> list = auUserService.getResourceByUserId(auId);
		return list;
	}
	
	public String getStrByList(List<Map<String,Object>> list, String key) throws Exception{
		StringBuffer sb = new StringBuffer();
		for(int i=0;i<list.size();i++){
			if(null != list.get(i).get(key) && !"".equals(list.get(i).get(key).toString())){
				sb.append(list.get(i).get(key).toString()).append(",");
			}
		}
		return sb.toString();
	}
	
	/**
	 * 根据用户Id进行登录，不进行数据校验
	 * @author yangcd
	 * @param uid 用户主键编号
	 * @throws Exception 
	 * */
	public Map<String, Object> loginByUserId(String uid, HttpServletRequest request, String loginType) throws Exception {
		SysUserInfo user = auUserService.findUserById(uid);
		Map<String, Object> dataMap = new HashMap<String, Object>();
		dataMap.put("userInfo", user);
		dataMap.put("sysRoleVoList", this.getStrByList(this.getRoleByUserId(user.getUserInfoNo()),"AR_CODE"));
		if("pc".equals(loginType)) {
			List<Menu> sysMenuVoList = menuService.createMenu(user.getLoginName(), uid);
			List<Map<String,Object>> rolePermissionVoList = this.getResourceByUserId(user.getUserInfoNo());
			dataMap.put("rolePermissionVoList", rolePermissionVoList);
			dataMap.put("rolePermissionVoStr", this.getStrByList(rolePermissionVoList,"PERMISSION"));
			dataMap.put("sysMenuVoList", sysMenuVoList);
		}
		
		//保存用户信息
		request.getSession().setAttribute(Constant.LOGIN_USER, user);
		return this.loginReturnMap(user, dataMap);
	}

	/**
	 * 根据用户loginName查询系统内用户信息
	 * @author yangcd
	 * @param loginName 登录名
	 * @throws Exception 
	 * */
	public List<Map<String, Object>> getUserListByUserName(String loginName)  throws Exception{
		List<Map<String, Object>> list = auUserService.getUserListByUserName(loginName);
		return list;
	}

	public Map<String, Object> wxLogin(String id, HttpServletRequest request, String string) {
		return null;
	}
	
	/**
	 * pc端登录方法
	 * @author yangcd
	 * */
	public Map<String, Object> login(String id, String userName, HttpServletRequest request, String loginType) throws Exception{
		SysUserInfo user = null;
		if("wx".equals(loginType)) {
			user = auUserService.findUserById(id);
		}else {
			user = auUserService.findUserByName(userName);
		}
		Map<String, Object> dataMap = new HashMap<String, Object>();
		dataMap.put("userInfo", user);
		dataMap.put("sysRoleVoList", this.getStrByList(this.getRoleByUserId(user.getUserInfoNo()),"AR_CODE"));
		if("pc".equals(loginType)) {
			List<Menu> sysMenuVoList = menuService.createMenu(userName, user.getUserInfoNo());
			List<Map<String,Object>> rolePermissionVoList = this.getResourceByUserId(user.getUserInfoNo());
			dataMap.put("rolePermissionVoList", rolePermissionVoList);
			dataMap.put("rolePermissionVoStr", this.getStrByList(rolePermissionVoList,"PERMISSION"));
			dataMap.put("sysMenuVoList", sysMenuVoList);
		}
		//保存用户信息
		request.getSession().setAttribute(Constant.LOGIN_USER, user);
		return this.loginReturnMap(user, dataMap);
	}

	/**
	 * pc端登录方法
	 * @author yangcd
	 * */
	public Map<String, Object> ssoLogin(String code,String accessToken,String openId, String loginType,HttpServletRequest request) throws Exception{
		Map<String, Object> dataMap = new HashMap<String, Object>();
		SysUserInfo user = auUserService.findUserByOpenId(openId);
		if(user!=null){
			String userName = user.getLoginName();
			String id = user.getUserInfoNo();
			if("wx".equals(loginType)) {
				user = auUserService.findUserById(id);
			}else {
				user = auUserService.findUserByName(userName);
			}
			user.setCode(code);
			user.setAccess_token(accessToken);
			dataMap.put("userInfo", user);
			dataMap.put("sysRoleVoList", this.getStrByList(this.getRoleByUserId(user.getUserInfoNo()),"AR_CODE"));
			if("pc".equals(loginType)) {
				List<Menu> sysMenuVoList = menuService.createMenu(userName, user.getUserInfoNo());
				List<Map<String,Object>> rolePermissionVoList = this.getResourceByUserId(user.getUserInfoNo());
				dataMap.put("rolePermissionVoList", rolePermissionVoList);
				dataMap.put("rolePermissionVoStr", this.getStrByList(rolePermissionVoList,"PERMISSION"));
				dataMap.put("sysMenuVoList", sysMenuVoList);
			}
			//保存用户信息
			request.getSession().setAttribute(Constant.LOGIN_USER, user);
			return this.loginReturnMap(user, dataMap);
		}else{
			return this.loginReturnMap(user, dataMap);
		}
	}
	public List<SysUserInfo> searchUserByOpenid(String openid) {
		return auUserService.searchUserByOpenid(openid);
	}
}
